package com.webdiy.hr.impl;

import com.sys.plat.bean.PageBean;
import com.sys.plat.service.base.BaseServiceImpl;
import com.sys.plat.util.HttpUtil;
import com.sys.system.Constants;
import com.sys.tool.HttpClientSuperTool;
import com.sys.tool.HttpClientTool;
import com.sys.tool.StringTool;
import com.sys.web.util.SystemUtil;
import com.webdiy.dao.model.HrConfig;
import com.webdiy.dao.model.HrInfo;
import com.webdiy.dao.model.ListView;
import com.webdiy.hr.iface.HrConfigSerice;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by IntelliJ IDEA.
 * User: mabo
 * Date: 2010-2-9
 * Time: 9:32:38
 * To change this template use File | Settings | File Templates.
 */
public class HrConfigSericeImpl extends BaseServiceImpl implements HrConfigSerice {


    public List<ListView> findList() {
        List<ListView> returnList = new ArrayList<ListView>();

        List<HrConfig> hcList = dao.listByHql("FROM HrConfig");

        List<HrInfo> hiList;
        for (HrConfig hrConfig : hcList) {
            ListView lv = new ListView();
            lv.setId(hrConfig.getId());
            lv.setCol1(hrConfig.getName());
            lv.setCol2(hrConfig.getHrWebName());


            hiList = dao.listByHql("FROM HrInfo WHERE hrConfig = ?", hrConfig.getId());


            Map<String, String> companyMap = new HashMap<String, String>();
            int send = 0;//等待发送数
            int send3 = 0;//等待选择无EMAIL
            int send3Mail = 0;//待选有EMAIL
            int noSend = 0;//放弃职位
            int finish = 0;//已发送数
            for (HrInfo hrInfo : hiList) {
                companyMap.put(hrInfo.getCompanyName(), "");
                if (hrInfo.getFinish().equals("2")) {
                    finish++;
                } else if (hrInfo.getFinish().equals("1") && (hrInfo.getSend().equals("1") || hrInfo.getSend().equals("4"))) {
                    send++;
                }
                if (hrInfo.getSend().equals("2")) {
                    noSend++;
                } else if (hrInfo.getSend().equals("3")) {
                    if (hrInfo.getMail() != null && !hrInfo.getMail().equals("")) {
                        send3Mail++;
                    } else {
                        send3++;
                    }
                }
            }

            lv.setCol3(String.valueOf(hiList.size()));//职位总数
            lv.setCol4(String.valueOf(send3));//等待选择数无Email
            lv.setCol5(String.valueOf(send3Mail));//等待选择数有Email
            lv.setCol6(String.valueOf(send));//等待发送数
            lv.setCol7(String.valueOf(finish));//已发送数
            lv.setCol8(String.valueOf(noSend));//放弃职位

            returnList.add(lv);
        }

        return returnList;
    }

    public void saveOrUpdate(HrConfig hc) {
        dao.saveOrUpdateObject(hc);
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public HrConfig editHrConfig(String id) {
        return (HrConfig) dao.getObject(HrConfig.class, id);
    }


    private volatile Map maps;

    public void loadDate(String hcId, final Map map) {
        maps = map;
        maps.put("callPageNo", 0);

        final HrConfig hc = (HrConfig) dao.getObject(HrConfig.class, hcId);

        Thread th = new Thread(new Runnable() {
            public void run() {
                if (hc.getHrWebName().equals("智联招聘")) {
                    callZhaoPinPage(hc);
                    callZhapPinJobPage(hc.getId());
                } else if (hc.getHrWebName().equals("51JOB")) {
                    call51JobPage(hc);
                    call51JopJobPage(hc.getId());
                }
            }
        });
        th.start();

    }


    /**
     * 智联招聘网站职位抓取程序
     *
     * @param hc
     */
    private void callZhaoPinPage(HrConfig hc) {
//        HrConfig hc = (HrConfig) dao.getObject(HrConfig.class, hcId);


HttpClientTool hct = new HttpClientTool();
        StringTool st = new StringTool();

        //String uri = "http://search.zhaopin.com/jobs_nv/jobsearchlistadv.asp?ShowMore=y&page=1&Keyword=%E8%BF%90%E8%90%A5&SchJobType=160000&JobLocation=530&EmplType=2%3B1&industry=210500%3B160400%3B160600&PublishDate=7";
        String uri = hc.getUri();
        hct.setUrl(uri);

        st.setPattern("第 <b class=\"blue12 num\">([\\d/]*)</b> 页");
        st.setMatcher(hct.getInnerHTML());


        int pNo = 0;
        if (st.isFind()) {
            //log.warn(st.getValue(1));
            pNo = Integer.valueOf(st.getValue(1).split("/")[1]);
        }
        maps.put("Step", "1");//步骤1
        maps.put("pageCount", pNo);//抓取职位列表总页数

        for (int j = 1; j < pNo; j++) {
            //uri = "http://search.zhaopin.com/jobs_nv/jobsearchlistadv.asp?page="+j+"&SchJobType=160000&subJobtype=&JobLocation=530&industry=210500%3B160400%3B160600&PublishDate=7&WorkingExp=&EduLevel=&CompanyType=&CompanySize=&EmplType_h=2%3B1&SalaryFrom_h=&SalaryTo_h=&keyType_h=&sortby=&ShowMore=y&SearchModel=0&f_kw=&KeyWord=%E8%BF%90%E8%90%A5&keywordtype=1&SchWorkingTimeAdv=&SchEduLevelAdv=&SchComptypeAdv=&SchCompsizeAdv=&EmplType=2&EmplType=1&SchSalaryFromAdv=0&SchSalaryToAdv=&DYWE=1262845535122.347681.1262845535.1262845535.1";
            st.setPattern("&page=\\d*&");
            st.setMatcher(uri);
            uri = st.replace("&page=" + j + "&");
            hct.setUrl(uri);
            st.setPattern("<td[^>]*?id=\"dvJobTit2\"[^>]*?>[^>]*?href=\"([^\"]*?)\"([^>]*?)>([^<]*?)<((?!td).)*?</td>");
            st.setMatcher(hct.getInnerHTML());

            String[] job_uri = st.getValues(1);
            String[] job_name = st.getValues(3);

            st.setPattern("<td[^>]*?id=\"dvCompNM\"[^>]*?>[^>]*?href=\"([^\"]*?)\"([^>]*?)>([^<]*?)<((?!td).)*?</td>");

            String[] comp_name = st.getValues(3);


            Session session = dao.getHibernateTemplate().getSessionFactory().openSession();
            Transaction t = session.beginTransaction();
            t.begin();
            for (int i = 0; i < job_name.length; i++) {


                String n = job_name[i];
                String u = job_uri[i];

                List list = dao.listByHql("FROM HrInfo hi left join fetch hi.hrConfig WHERE  hi.jobUrl=? AND hi.hrConfig.gftUserInfo.id = ?", u, SystemUtil.getLoginUser().getGftUserInfo().getId());
                if (list.size() > 0) {
                    continue;
                }

                //System.out.println(n + " == " + u);

                HrInfo hr = new HrInfo();
                hr.setJobName(n);
                hr.setJobUrl(u);
                hr.setCompanyName(comp_name[i]);
                hr.setHrConfig(hc);

                session.saveOrUpdate(hr);
            }
            t.commit();
            session.close();
            maps.put("pageNo", j);//抓取职位列表已完成页数
        }


    }


    /**
     * 智联招聘，职位信息补全程序
     *
     * @param hcId
     */
    private void callZhapPinJobPage(final String hcId) {
        maps.put("Step", "2");//步骤2

        final List<HrInfo> list = dao.listByHql("FROM HrInfo WHERE ready = '1' AND hrConfig = ?", hcId);
        maps.put("callPageCount", list.size());//职位总数


        ExecutorService es = Executors.newFixedThreadPool(5);
        for (final HrInfo hrInfo : list) {
            es.execute(new Runnable() {
                public void run() {


                    synchronized (maps) {
                        int i = Integer.valueOf(maps.get("callPageNo").toString());
                        i++;
                        maps.put("callPageNo", i);//已抓取完毕职位数
                    }

                    StringTool st = new StringTool();

HttpClientTool hct = new HttpClientTool();
                    hct.setUrl(hrInfo.getJobUrl());

                    st.setPattern("<div class=\"jobDes\">([^!|!]*?)</div>");//说明
                    st.setMatcher(hct.getInnerHTML());

                    hrInfo.setJobDesc(st.getValue(1));


                    st.setPattern("<div class=\"jobContact\">([^!|!]*?)</div>");//联系方式

                    hrInfo.setContacts(st.getValue(1));


                    st.setPattern("<a(.*?)EmailClick(.*?)>([\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+)</a>");
                    List<String> mails = new ArrayList();
                    Collections.addAll(mails, st.getValues(3));

                    HashSet hSet = new HashSet();
                    hSet.addAll(mails);
                    mails.clear();
                    mails.addAll(hSet);

                    StringBuffer sb = new StringBuffer();
                    for (String mail : mails) {
                        sb.append(mail).append(",");
                    }

                    if (sb.toString().length() > 0)
                        hrInfo.setMail(sb.toString().substring(0, sb.toString().length() - 1));


                    st.setPattern("<span id=\"span4freshdate\">([\\d-]*)</span>");
                    hrInfo.setPubDate(st.getValue(1));

                    st.setPattern("var arrVarFromASP = \\[((.)*?)\\]");
                    hrInfo.setJobId(st.getValue(1).replaceAll("'", "").split(",")[1]);

                    hrInfo.setReady("2");
                    dao.updateObject(hrInfo);

                    //log.warn(hrInfo.getCompanyName());


                }
            });
        }
    }


    /**
     * 51Job网站职位抓取程序
     *
     * @param hc
     */
    private void call51JobPage(HrConfig hc) {
//        HrConfig hc = (HrConfig) dao.getObject(HrConfig.class, hcId);


        HttpClientSuperTool hct = new HttpClientSuperTool();
        StringTool st = new StringTool();
        hct.setHost("search.51job.com");
        //String uri = "http://search.zhaopin.com/jobs_nv/jobsearchlistadv.asp?ShowMore=y&page=1&Keyword=%E8%BF%90%E8%90%A5&SchJobType=160000&JobLocation=530&EmplType=2%3B1&industry=210500%3B160400%3B160600&PublishDate=7";
        String uri = hc.getUri();
        hct.execute(uri);

        st.setPattern("<td>([\\d- /]*)</td>");
        st.setMatcher(hct.getHtmlBody());


        int pNo = 0;
        if (st.isFind()) {
            //log.warn(st.getValue(1));
            pNo = Integer.valueOf(st.getValue(1).split("/")[1].trim()) / 30;
        }
        maps.put("Step", "1");//步骤1
        maps.put("pageCount", pNo);//抓取职位列表总页数

        for (int j = 1; j < pNo; j++) {
            //uri = "http://search.zhaopin.com/jobs_nv/jobsearchlistadv.asp?page="+j+"&SchJobType=160000&subJobtype=&JobLocation=530&industry=210500%3B160400%3B160600&PublishDate=7&WorkingExp=&EduLevel=&CompanyType=&CompanySize=&EmplType_h=2%3B1&SalaryFrom_h=&SalaryTo_h=&keyType_h=&sortby=&ShowMore=y&SearchModel=0&f_kw=&KeyWord=%E8%BF%90%E8%90%A5&keywordtype=1&SchWorkingTimeAdv=&SchEduLevelAdv=&SchComptypeAdv=&SchCompsizeAdv=&EmplType=2&EmplType=1&SchSalaryFromAdv=0&SchSalaryToAdv=&DYWE=1262845535122.347681.1262845535.1262845535.1";
            st.setPattern("&curr_page=\\d*&");
            st.setMatcher(uri);
            if (st.isFind()) {
                uri = st.replace("&curr_page=" + j + "&");
            } else {
                st.setPattern("&curr_page=\\d*");
                st.setMatcher(uri);
                if (st.isFind()) {
                    uri = st.replace("&curr_page=" + j);
                } else {
                    if (uri.indexOf("curr_page") > 0) {
                        uri = uri + j;
                    } else {
                        uri = uri + "&curr_page=" + j;
                    }
                }
            }

            System.out.println(uri);
            hct.execute(uri);
            st.setPattern("<td class=\"td1\">(.|^.)*?<a(.|^.)*?href=\"((.|^.)*?)\"(.|^.)*?>((.|^.)*?)</a><img((.|^.)*?)</td>");
            st.setMatcher(hct.getHtmlBody());

            String[] job_uri = st.getValues(3);
            String[] job_name = st.getValues(6);

            st.setPattern("<td class=\"td2\">(.|^.)*?<a(.|^.)*?>((.|^.)*?)</a></td>");

            String[] comp_name = st.getValues(3);

            st.setPattern("<font color=\"#fe0201\">((.|^.)*?)</font>");
            for (int i = 0; i < job_name.length; i++) {
                String s = job_name[i];
                st.setMatcher(s);
                if (st.isFind()) {
                    job_name[i] = st.replace(st.getValue(1));
                }
            }


            Session session = dao.getHibernateTemplate().getSessionFactory().openSession();
            Transaction t = session.beginTransaction();
            t.begin();
            for (int i = 0; i < job_name.length; i++) {


                String n = job_name[i];
                String u = job_uri[i];


                List list = dao.listByHql("FROM HrInfo hi left join fetch hi.hrConfig WHERE  hi.jobUrl=? AND hi.hrConfig.gftUserInfo.id = ?", u, SystemUtil.getLoginUser().getGftUserInfo().getId());
                //List list = dao.listByHql("FROM HrInfo WHERE  jobUrl=? AND hrConfig = ?", u, hc.getId());
                if (list.size() > 0) {
                    continue;
                }

                //System.out.println(n + " == " + u);

                HrInfo hr = new HrInfo();
                hr.setJobName(n);
                hr.setJobUrl(u);
                hr.setCompanyName(comp_name[i]);
                hr.setHrConfig(hc);

                session.saveOrUpdate(hr);
            }
            t.commit();
            session.close();
            maps.put("pageNo", j);//抓取职位列表已完成页数
        }
    }


    /**
     * 智联招聘，职位信息补全程序
     *
     * @param hcId
     */
    private void call51JopJobPage(final String hcId) {
        maps.put("Step", "2");//步骤2

        final List<HrInfo> list = dao.listByHql("FROM HrInfo WHERE ready = '1' AND hrConfig = ?", hcId);
        maps.put("callPageCount", list.size());//职位总数


        ExecutorService es = Executors.newFixedThreadPool(5);
        for (final HrInfo hrInfo : list) {
            es.execute(new Runnable() {
                public void run() {


                    synchronized (maps) {
                        int i = Integer.valueOf(maps.get("callPageNo").toString());
                        i++;
                        maps.put("callPageNo", i);//已抓取完毕职位数
                    }

                    StringTool st = new StringTool();

                    try {


                        HttpClientSuperTool hct = new HttpClientSuperTool();
                        hct.setHost("search.51job.com");
                        hct.execute(hrInfo.getJobUrl());

                        st.setPattern("<td colspan=\"6\" class=\"txt_4 wordBreakNormal job_detail\">((.|^.)*?)</td>");//说明
                        String h = hct.getHtmlBody();
                        h.replaceAll("\\?xmls:", "");
                        st.setMatcher(h);

                        hrInfo.setJobDesc(st.getValue(1));


                        st.setPattern("<a(.*?)mailto(.*?)>([\\w-]+(\\.[\\w-]+)*@[^51job][\\w-]+(\\.[\\w-]+)+)</a>");
                        List<String> mails = new ArrayList();
                        Collections.addAll(mails, st.getValues(3));


                        HashSet hSet = new HashSet();
                        hSet.addAll(mails);
                        mails.clear();
                        mails.addAll(hSet);

                        StringBuffer sb = new StringBuffer();
                        for (String mail : mails) {
                            sb.append(mail).append(",");
                        }

                        if (sb.toString().length() > 0)
                            hrInfo.setMail(sb.toString().substring(0, sb.toString().length() - 1));


                        st.setPattern("<tr><td class=\"txt_1\">发布日期：</td><td class=\"txt_2\">([\\d-]*)</td>");
                        hrInfo.setPubDate(st.getValue(1));

                    } catch (Exception e) {
                        hrInfo.setSend("2");
                        dao.updateObject(hrInfo);
                        return;
                    }

                    hrInfo.setReady("2");
                    dao.updateObject(hrInfo);

                    //log.warn(hrInfo.getCompanyName());


                }
            });
        }
    }

    public void saveCoverLetter(HrConfig hc) {
        HrConfig h = (HrConfig) dao.getObject(HrConfig.class, hc.getId());
        h.setCoverLetter(hc.getCoverLetter());
        dao.saveOrUpdateObject(h);
    }

    public String[] getSendMailInfo(String configId) {
        HrConfig hc = (HrConfig) dao.getObject(HrConfig.class, configId);
        String[] s = {hc.getSendMail(), hc.getMailPwd(), hc.getSmtp()};
        return s;
    }

    public void saveSendMailInfo(HrConfig hc) {
        HrConfig h = (HrConfig) dao.getObject(HrConfig.class, hc.getId());
        h.setSendMail(hc.getSendMail());
        h.setMailPwd(hc.getMailPwd());
        h.setSmtp(hc.getSmtp());
        dao.updateObject(h);
    }

    public boolean saveWebLoginInfo(HrConfig hc) {
        HrConfig h = (HrConfig) dao.getObject(HrConfig.class, hc.getId());
        h.setWebName(hc.getWebName());
        h.setWebPassWord(hc.getWebPassWord());
        dao.updateObject(h);
        return true;  //To change body of implemented methods use File | Settings | File Templates.
    }

}